package com.xxwy.lifecycle.resolvable;

import com.xxwy.lifecycle.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.List;
import java.util.Optional;

/**
 * 非spring ioc 容器内管对管理对象.
 *
 * @author xxwy
 * @date 2021/7/13 0013
 */
public class ResolvableDependencyTest {

    @Autowired
    private Optional<List<User>> user;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(ResolvableDependencyTest.class);

        // 方案1：register后，refresh请register
        DefaultListableBeanFactory listableBeanFactory = applicationContext.getDefaultListableBeanFactory();
        //     外部ResolvableDependency
        listableBeanFactory.registerResolvableDependency(User.class, new User("xx", 1));
        // 方案2：addBeanFactory回调函数
        applicationContext.addBeanFactoryPostProcessor(beanFactory -> beanFactory.registerResolvableDependency(User.class, new User("xxx", 2)));



        // 内部：debug: AbstractApplicationContext.prepareBeanFactory： registerResolvableDependency
        applicationContext.refresh();
        // 依赖查找: {}
        System.out.println(listableBeanFactory.getBeansOfType(User.class));

        // 依赖注入 Optional[com.xxwy.source.bean.User。。。] 不为空
        ResolvableDependencyTest bean = applicationContext.getBean(ResolvableDependencyTest.class);
        // [User(name=xxx, age=2)]
        System.out.println(bean.user.get());

        applicationContext.close();
    }
}
